<template>
  <div class="users-container">
    <el-card class="users-card">
      <div class="page-actions">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索用户名/邮箱"
          clearable
          @clear="handleSearch"
          style="width: 250px;"
        >
          <template #append>
            <el-button :icon="Search" @click="handleSearch" />
          </template>
        </el-input>
        
        <el-dropdown @command="handleImportExport" split-button type="primary">
          <el-icon class="el-icon--left"><Upload /></el-icon>导入/导出
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="import">
                <el-icon><Upload /></el-icon>导入用户
              </el-dropdown-item>
              <el-dropdown-item command="export">
                <el-icon><Download /></el-icon>导出用户
              </el-dropdown-item>
              <el-dropdown-item command="template">
                <el-icon><Document /></el-icon>下载模板
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        
        <el-button type="danger" :disabled="!selectedUsers.length" @click="handleBatchDelete">
          <el-icon><Delete /></el-icon>批量删除
        </el-button>
        
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>新增用户
        </el-button>
    </div>
      <el-table 
        :data="filteredUserList" 
        style="width: 100%" 
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="用户名" width="120" />
        <el-table-column prop="role" label="角色" width="120" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="'启用'"
              :inactive-value="'禁用'"
              @change="(val) => handleStatusChange(scope.row, val)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220">
          <template #default="scope">
            <el-button size="small" type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="warning" link @click="handleResetPassword(scope.row)">重置密码</el-button>
            <el-button size="small" type="danger" link @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalUsers"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="queryParams.pageSize"
          :current-page="queryParams.page"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 用户表单对话框 -->
    <el-dialog
      :title="dialogType === 'add' ? '新增用户' : '编辑用户'"
      v-model="dialogVisible"
      width="500px"
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="userRules"
        label-width="100px"
        status-icon
      >
        <el-form-item label="用户名" prop="name">
          <el-input v-model="userForm.name" placeholder="请输入用户名" />
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        
        <el-form-item label="角色" prop="role">
          <el-select v-model="userForm.role" placeholder="请选择角色" style="width: 100%">
            <el-option label="管理员" value="管理员" />
            <el-option label="编辑" value="编辑" />
            <el-option label="普通用户" value="普通用户" />
            <el-option label="访客" value="访客" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="密码" prop="password" v-if="dialogType === 'add'">
          <el-input v-model="userForm.password" type="password" placeholder="请输入密码" show-password />
        </el-form-item>
        
        <el-form-item label="确认密码" prop="confirmPassword" v-if="dialogType === 'add'">
          <el-input v-model="userForm.confirmPassword" type="password" placeholder="请确认密码" show-password />
        </el-form-item>
        
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        
        <el-form-item label="部门" prop="department">
          <el-input v-model="userForm.department" placeholder="请输入部门" />
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="userForm.status"
            :active-value="'启用'"
            :inactive-value="'禁用'"
            active-text="启用"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitLoading">确认</el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 删除确认对话框 -->
    <el-dialog
      title="删除确认"
      v-model="deleteDialogVisible"
      width="400px"
    >
      <div class="delete-confirm">
        <el-icon class="warning-icon" color="#ff4d4f" :size="24"><WarningFilled /></el-icon>
        <p>确定要删除用户 <strong>{{ deleteUser.name }}</strong> 吗？此操作不可恢复！</p>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmDelete" :loading="deleteLoading">确认删除</el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 批量删除确认对话框 -->
    <el-dialog
      title="批量删除确认"
      v-model="batchDeleteDialogVisible"
      width="400px"
    >
      <div class="delete-confirm">
        <el-icon class="warning-icon" color="#ff4d4f" :size="24"><WarningFilled /></el-icon>
        <p>确定要删除选中的 <strong>{{ selectedUsers.length }}</strong> 个用户吗？此操作不可恢复！</p>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="batchDeleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmBatchDelete" :loading="deleteLoading">确认删除</el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 导入用户对话框 -->
    <el-dialog
      title="导入用户"
      v-model="importDialogVisible"
      width="500px"
    >
      <div class="import-container">
        <el-upload
          class="upload-demo"
          drag
          action="#"
          :auto-upload="false"
          :on-change="handleFileChange"
          accept=".xlsx,.xls,.csv"
        >
          <el-icon class="el-icon--upload"><Upload /></el-icon>
          <div class="el-upload__text">
            拖拽文件到此处或 <em>点击上传</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              只能上传 xlsx/xls/csv 文件，且不超过 10MB
            </div>
          </template>
        </el-upload>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="importDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmImport" :loading="importLoading">导入</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Search, WarningFilled, Upload, Download, Document, 
  User, Plus, Delete
} from '@element-plus/icons-vue'
import { SystemUser, UserForm, QueryParams } from '@/types'
import { 
  getUserList, 
  createUser, 
  updateUser, 
  deleteUser, 
  batchDeleteUsers, 
  updateUserStatus,
  resetUserPassword
} from '@/api/user'

// 查询参数
const queryParams = reactive<QueryParams>({
  page: 1,
  pageSize: 10,
  keyword: ''
})

// 表格数据和分页
const loading = ref(false)
const totalUsers = ref(0)
const searchKeyword = ref('')
const selectedUsers = ref<SystemUser[]>([])
const userList = ref<SystemUser[]>([])

// 对话框控制
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const submitLoading = ref(false)
const deleteDialogVisible = ref(false)
const batchDeleteDialogVisible = ref(false)
const deleteLoading = ref(false)
const deleteUser = ref<SystemUser>({} as SystemUser)
const importDialogVisible = ref(false)
const importLoading = ref(false)
const importFile = ref<File | null>(null)

// 表单引用
const userFormRef = ref()

// 用户表单数据
const userForm = reactive<UserForm>({
  id: '',
  name: '',
  email: '',
  role: '',
  password: '',
  confirmPassword: '',
  status: '启用',
  phone: '',
  department: ''
})

// 表单验证规则
const userRules = {
  name: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur', validator: (rule: any, value: string, callback: any) => {
      if (dialogType.value === 'add' && !value) {
        callback(new Error('请输入密码'))
      } else {
        callback()
      }
    }},
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur', validator: (rule: any, value: string, callback: any) => {
      if (dialogType.value === 'add' && !value) {
        callback(new Error('请确认密码'))
      } else if (value !== userForm.password) {
        callback(new Error('两次输入密码不一致'))
      } else {
        callback()
      }
    }}
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
}

// 根据搜索关键词筛选用户
const filteredUserList = computed(() => {
  if (!searchKeyword.value) {
    return userList.value
  }
  
  const keyword = searchKeyword.value.toLowerCase()
  return userList.value.filter(user => 
    user.name.toLowerCase().includes(keyword) || 
    user.email.toLowerCase().includes(keyword)
  )
})

// 处理表格选择变化
const handleSelectionChange = (selection: SystemUser[]) => {
  selectedUsers.value = selection
}

// 加载用户数据
const loadData = async () => {
  loading.value = true
  
  try {
    // 实际项目中使用API调用
    // const res = await getUserList(queryParams)
    // userList.value = res.data.list
    // totalUsers.value = res.data.total
    
    // 模拟API调用
    setTimeout(() => {
      // 模拟数据
      if (userList.value.length === 0) {
        userList.value = [
          {
            id: 1,
            name: 'admin',
            role: '管理员',
            email: 'admin@example.com',
            createTime: '2025-01-01 12:00:00',
            status: '启用',
            phone: '13800001234',
            department: '技术部',
            lastLoginTime: '2025-01-10 08:30:00'
          },
          {
            id: 2,
            name: 'user1',
            role: '普通用户',
            email: 'user1@example.com',
            createTime: '2025-01-02 10:30:00',
            status: '启用',
            phone: '13800002345',
            department: '市场部',
            lastLoginTime: '2025-01-09 14:20:00'
          },
          {
            id: 3,
            name: 'user2',
            role: '普通用户',
            email: 'user2@example.com',
            createTime: '2025-01-03 15:20:00',
            status: '禁用',
            phone: '13800003456',
            department: '财务部',
            lastLoginTime: '2025-01-05 09:45:00'
          },
          {
            id: 4,
            name: 'editor',
            role: '编辑',
            email: 'editor@example.com',
            createTime: '2025-01-04 09:15:00',
            status: '启用',
            phone: '13800004567',
            department: '内容部',
            lastLoginTime: '2025-01-08 16:10:00'
          },
          {
            id: 5,
            name: 'guest',
            role: '访客',
            email: 'guest@example.com',
            createTime: '2025-01-05 14:40:00',
            status: '禁用',
            phone: '13800005678',
            department: '客服部',
            lastLoginTime: '2025-01-06 11:30:00'
          },
          {
            id: 6,
            name: 'guest',
            role: '访客',
            email: 'guest@example.com',
            createTime: '2025-01-05 14:40:00',
            status: '禁用',
            phone: '13800005678',
            department: '客服部',
            lastLoginTime: '2025-01-06 11:30:00'
          },
          {
            id: 7,
            name: 'guest',
            role: '访客',
            email: 'guest@example.com',
            createTime: '2025-01-05 14:40:00',
            status: '禁用',
            phone: '13800005678',
            department: '客服部',
            lastLoginTime: '2025-01-06 11:30:00'
          },
          {
            id: 8,
            name: 'guest',
            role: '访客',
            email: 'guest@example.com',
            createTime: '2025-01-05 14:40:00',
            status: '禁用',
            phone: '13800005678',
            department: '客服部',
            lastLoginTime: '2025-01-06 11:30:00'
          },
          {
            id: 9,
            name: 'guest',
            role: '访客',
            email: 'guest@example.com',
            createTime: '2025-01-05 14:40:00',
            status: '禁用',
            phone: '13800005678',
            department: '客服部',
            lastLoginTime: '2025-01-06 11:30:00'
          },
          {
            id: 10,
            name: 'guest',
            role: '访客',
            email: 'guest@example.com',
            createTime: '2025-01-05 14:40:00',
            status: '禁用',
            phone: '13800005678',
            department: '客服部',
            lastLoginTime: '2025-01-06 11:30:00'
          }
        ]
      }
      
      totalUsers.value = 100
      loading.value = false
    }, 500)
  } catch (error) {
    console.error('加载用户数据失败', error)
    ElMessage.error('加载用户数据失败')
    loading.value = false
  }
}

// 处理每页条数变化
const handleSizeChange = (size: number) => {
  queryParams.pageSize = size
  loadData()
}

// 处理页码变化
const handleCurrentChange = (page: number) => {
  queryParams.page = page
  loadData()
}

// 处理搜索
const handleSearch = () => {
  queryParams.page = 1
  queryParams.keyword = searchKeyword.value
  loadData()
}

// 处理状态变更
const handleStatusChange = async (row: SystemUser, value: string) => {
  const statusText = value === '启用' ? '启用' : '禁用'
  
  try {
    // 实际项目中使用API调用
    // await updateUserStatus(row.id, value)
    
    // 模拟API调用
    ElMessage.success(`已${statusText}用户: ${row.name}`)
  } catch (error) {
    // 恢复状态
    row.status = row.status === '启用' ? '禁用' : '启用'
    ElMessage.error(`操作失败`)
  }
}

// 重置表单
const resetForm = () => {
  userForm.id = ''
  userForm.name = ''
  userForm.email = ''
  userForm.role = ''
  userForm.password = ''
  userForm.confirmPassword = ''
  userForm.status = '启用'
  userForm.phone = ''
  userForm.department = ''
  
  nextTick(() => {
    userFormRef.value?.clearValidate()
  })
}

// 处理新增用户
const handleAdd = () => {
  dialogType.value = 'add'
  resetForm()
  dialogVisible.value = true
}

// 处理编辑用户
const handleEdit = (row: SystemUser) => {
  dialogType.value = 'edit'
  resetForm()
  
  userForm.id = row.id
  userForm.name = row.name
  userForm.email = row.email
  userForm.role = row.role
  userForm.status = row.status
  userForm.phone = row.phone || ''
  userForm.department = row.department || ''
  
  dialogVisible.value = true
}

// 处理删除用户
const handleDelete = (row: SystemUser) => {
  deleteUser.value = row
  deleteDialogVisible.value = true
}

// 处理批量删除
const handleBatchDelete = () => {
  if (selectedUsers.value.length === 0) {
    ElMessage.warning('请至少选择一个用户')
    return
  }
  
  batchDeleteDialogVisible.value = true
}

// 处理重置密码
const handleResetPassword = (row: SystemUser) => {
  ElMessageBox.confirm(
    `确定要重置用户 ${row.name} 的密码吗？`,
    '重置密码',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(async () => {
      try {
        // 实际项目中使用API调用
        // await resetUserPassword(row.id)
        
        // 模拟API调用
        ElMessage.success(`已重置用户 ${row.name} 的密码为默认密码`)
      } catch (error) {
        ElMessage.error('重置密码失败')
      }
    })
    .catch(() => {
      // 用户取消操作
    })
}

// 处理导入导出
const handleImportExport = (command: string) => {
  switch (command) {
    case 'import':
      importDialogVisible.value = true
      break
    case 'export':
      // 模拟导出
      ElMessage.success('已开始导出用户数据，请稍候...')
      setTimeout(() => {
        ElMessage.success('导出成功')
      }, 1000)
      break
    case 'template':
      // 模拟下载模板
      ElMessage.success('正在下载导入模板...')
      setTimeout(() => {
        ElMessage.success('模板下载成功')
      }, 1000)
      break
  }
}

// 处理文件变更
const handleFileChange = (file: any) => {
  importFile.value = file.raw
}

// 确认导入
const confirmImport = async () => {
  if (!importFile.value) {
    ElMessage.warning('请选择要导入的文件')
    return
  }
  
  // 检查文件类型和大小
  const validTypes = ['.xlsx', '.xls', '.csv']
  const isValidType = validTypes.some(type => 
    importFile.value!.name.toLowerCase().endsWith(type)
  )
  
  if (!isValidType) {
    ElMessage.error('文件类型不正确，请上传 Excel 或 CSV 文件')
    return
  }
  
  const isValidSize = importFile.value.size / 1024 / 1024 < 10
  if (!isValidSize) {
    ElMessage.error('文件大小不能超过 10MB')
    return
  }
  
  importLoading.value = true
  
  try {
    // 实际项目中这里应该有文件上传和处理逻辑
    
    // 模拟导入
    setTimeout(() => {
      importLoading.value = false
      importDialogVisible.value = false
      ElMessage.success('导入成功，已添加 5 条用户数据')
      
      // 重新加载数据
      loadData()
    }, 1500)
  } catch (error) {
    importLoading.value = false
    ElMessage.error('导入失败')
  }
}

// 确认删除
const confirmDelete = async () => {
  deleteLoading.value = true
  
  try {
    // 实际项目中使用API调用
    // await deleteUser(deleteUser.value.id)
    
    // 模拟API调用
    setTimeout(() => {
      // 从列表中移除用户
      const index = userList.value.findIndex(item => item.id === deleteUser.value.id)
      if (index !== -1) {
        userList.value.splice(index, 1)
      }
      
      deleteLoading.value = false
      deleteDialogVisible.value = false
      ElMessage.success('删除成功')
    }, 500)
  } catch (error) {
    deleteLoading.value = false
    ElMessage.error('删除失败')
  }
}

// 确认批量删除
const confirmBatchDelete = async () => {
  deleteLoading.value = true
  
  try {
    // 获取所有选中用户的ID
    const selectedIds = selectedUsers.value.map(user => user.id)
    
    // 实际项目中使用API调用
    // await batchDeleteUsers(selectedIds)
    
    // 模拟API调用
    setTimeout(() => {
      // 从列表中移除选中的用户
      userList.value = userList.value.filter(user => !selectedIds.includes(user.id))
      
      deleteLoading.value = false
      batchDeleteDialogVisible.value = false
      ElMessage.success(`成功删除 ${selectedIds.length} 个用户`)
      
      // 清空选中状态
      selectedUsers.value = []
    }, 500)
  } catch (error) {
    deleteLoading.value = false
    ElMessage.error('批量删除失败')
  }
}

// 提交表单
const submitForm = async () => {
  if (!userFormRef.value) return
  
  try {
    await userFormRef.value.validate()
    
    submitLoading.value = true
    
    if (dialogType.value === 'add') {
      // 添加新用户
      // 实际项目中使用API调用
      // const userData = {
      //   name: userForm.name,
      //   email: userForm.email,
      //   role: userForm.role,
      //   status: userForm.status,
      //   password: userForm.password,
      //   phone: userForm.phone,
      //   department: userForm.department
      // }
      // await createUser(userData)
      
      // 模拟API调用
      setTimeout(() => {
        const newUser: SystemUser = {
          id: userList.value.length + 1,
          name: userForm.name,
          email: userForm.email,
          role: userForm.role,
          status: userForm.status,
          createTime: new Date().toLocaleString(),
          phone: userForm.phone,
          department: userForm.department,
          lastLoginTime: '-'
        }
        
        userList.value.push(newUser)
        ElMessage.success('添加成功')
        
        submitLoading.value = false
        dialogVisible.value = false
      }, 500)
    } else {
      // 更新现有用户
      // 实际项目中使用API调用
      // const userData = {
      //   name: userForm.name,
      //   email: userForm.email,
      //   role: userForm.role,
      //   status: userForm.status,
      //   phone: userForm.phone,
      //   department: userForm.department
      // }
      // await updateUser(userForm.id, userData)
      
      // 模拟API调用
      setTimeout(() => {
        const index = userList.value.findIndex(item => item.id === userForm.id)
        if (index !== -1) {
          userList.value[index] = {
            ...userList.value[index],
            name: userForm.name,
            email: userForm.email,
            role: userForm.role,
            status: userForm.status,
            phone: userForm.phone,
            department: userForm.department
          }
        }
        
        ElMessage.success('更新成功')
        
        submitLoading.value = false
        dialogVisible.value = false
      }, 500)
    }
  } catch (error) {
    console.error('表单验证失败', error)
    submitLoading.value = false
  }
}

onMounted(() => {
  loadData()
})
</script>

<style scoped>
.users-container {
  padding: var(--content-padding);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  background-color: white;
  padding: 16px 20px;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.page-title {
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: 600;
  color: var(--text-primary, #303133);
}

.page-title .el-icon {
  margin-right: 8px;
  font-size: 18px;
}

.page-actions {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
}

.users-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.delete-confirm {
  display: flex;
  align-items: center;
  gap: 12px;
}

.warning-icon {
  font-size: 24px;
  color: #ff4d4f;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

.import-container {
  display: flex;
  justify-content: center;
  padding: 20px 0;
}

.el-upload {
  width: 100%;
}

.el-upload-dragger {
  width: 100%;
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .page-actions {
    width: 100%;
    flex-wrap: wrap;
  }
}
</style> 